package it.blog.controller;

import it.blog.stub.*;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

public class AddPost extends HttpServlet{

	private static final long serialVersionUID = 1L;
	

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Post apost=new Post();
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		
		AuthBlogPortalService us= new AuthBlogPortalService();
		W3CEndpointReference ref=(W3CEndpointReference)session.getAttribute("ref");
		AuthBlogPortal userAuthenticate=us.getPort(ref, AuthBlogPortal.class);
		
		session.removeAttribute("mess");
		apost.setBlogID(Integer.parseInt(request.getParameter("blogID")));
		apost.setTitle(request.getParameter("titlePost"));
		apost.setContent(request.getParameter("contentPost"));
		apost.setImgURL(request.getParameter("imgURL"));
		apost.setCategory(Integer.parseInt(request.getParameter("postCategory")));
		apost.setCounterPostView(0);	
		apost.setWriter(user.getUserID());
		Calendar c = Calendar.getInstance();
		try {
			apost.setDate(toXMLGregorianCalendar(c));
		} catch (DatatypeConfigurationException e) {
			e.printStackTrace();
		}
		
		if(apost.getTitle()!=null && !apost.getTitle().isEmpty() && apost.getContent()!=null && !apost.getContent().isEmpty()) {

			boolean result=false;
			result = userAuthenticate.addPost(apost);
			if(result){
				response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+ "/BlogView?id="+apost.getBlogID()+"&var=blog&p=1"));
			}
			else{
				session.setAttribute("mess","Errore nell'inserimento del post");
				response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+ "/BlogView?id="+apost.getBlogID()+"&var=blog&p=1"));
			}
		}
		else{
			session.setAttribute("mess","Tutti i campi sono obbligatori");
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+ "/BlogView?id="+apost.getBlogID()+"&var=blog&p=1"));
		}
	}
	
	
	private static XMLGregorianCalendar toXMLGregorianCalendar(Calendar c) throws DatatypeConfigurationException {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(c.getTimeInMillis());
		XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);	
		return xc;
	}
	
}
